package com.bw.controller.alipay;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.controller.task.OrderSche;
import com.bw.entity.alipay.PiPayLog;
import com.bw.entity.order.PiOrder;
import com.bw.req.AliPayMany;
import com.bw.resp.ResponseResult;
import com.bw.service.alipay.IPiPayLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.utils.alipay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *  订单零件材料
 * @author yzz
 * @since 2020-06-20
 */
@RestController
@RequestMapping("/alipay")
public class AliPayConterller {

    @Autowired
    private IPiOrderService orderService;

    @Autowired
    private IPiPayLogService payLogService;

    private final Logger logger = LoggerFactory.getLogger(AliPayConterller.class);

    @RequestMapping("/checks")
    public ResponseResult checks(HttpServletRequest request){
        logger.info("开始判断并跳转支付返回页面");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            String no = request.getParameter("out_trade_no");
            String trade = request.getParameter("trade_no");
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",no);
            PiOrder one = orderService.getOne(queryWrapper);
            PiPayLog payLog = new PiPayLog();
            payLog.setOutTradeNo(no);
            payLog.setCreateTime(new Date());
            payLog.setTotalAmount(one.getPriceIt());
            payLog.setUserId(one.getUserid());
            payLog.setTradeNo(trade);
            payLog.setPayType("电脑交易");
            if(signVerified){
                logger.debug("成功");
                one.setState(4);
                payLog.setTradeState("交易成功");
                payLogService.save(payLog);
                orderService.saveOrUpdate(one);
                success.setMessage("支付成功");
            }else{
                logger.debug("失败");
                payLog.setTradeState("交易失败");
                payLogService.save(payLog);
                success.setSuccess(false);
                success.setMessage("支付失败");
            }
        }catch (Exception e){
            success.setSuccess(false);
            success.setMessage("失败"+e.toString());
        }
        logger.info("结束判断并跳转支付返回页面");
        return success;
    }

    /**
     * @Description:支付界面
     * @Author: 李钊毅
     * @Date: 2020/6/29 21:59
     * @param aliPayMany:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("pay")
    public ResponseResult pay(@RequestBody AliPayMany aliPayMany){
        logger.info("进入支付页面判断");
        ResponseResult success = ResponseResult.SUCCESS();
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ aliPayMany.getCode() +"\","//商品编号
                    + "\"total_amount\":\""+ aliPayMany.getPriceit() +"\","//商品应付款
                    + "\"subject\":\""+ aliPayMany.getCustomerName() +"\","
                    + "\"body\":\"sdsadsd\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //盗用支付宝接口返回form到支付页面
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            //开始支付的订单记录
            logger.info("开始支付的订单记录");
            PiPayLog payLog = new PiPayLog();
            payLog.setOutTradeNo(aliPayMany.getCode());
            payLog.setCreateTime(new Date());//---根据时间判断订单支付状态
            payLog.setTotalAmount(new BigDecimal(aliPayMany.getPriceit()));
            payLog.setTradeState("支付中..."+0);//0表示待支付
            payLog.setPayType("电脑交易");
            payLogService.save(payLog);
            //输出
            success.setResult(result);
        }catch (Exception e){
            success.setSuccess(false);
            success.setMessage("发送失败"+e.toString());
        }
        logger.info("进入支付页面结束");
        return success;
    }
}
